<?php

namespace App\Http\Controllers;

use App\Http\Requests\UserAddressRequest;
use App\Models\UserAddress;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UserAddressesController extends Controller
{
    public function index(Request $request)
    {
        return view('user_addresses.index', [
            'addresses' => $request->user()->addresses,
        ]);
    }

    public function create()
    {
        return view('user_addresses.create_and_edit', ['address' => new UserAddress()]);
    }

    public function store(Request $request)
    {

        //return $request->bearerToken();
        $user = Auth::guard('api')->user();
        $address = $user->addresses()->create($request->only([

            // 'province',
            // 'city',
            // 'district',
            //'zip',
            'address',
            'contact_name',
            'contact_phone'
        ]));

        return response()->json(['meta'=>['status'=>200,'msg'=>'地址保存成功!'],'data'=>$address]);

    }

    public function edit(UserAddress $user_address)
    {
        $this->authorize('own', $user_address);
        return view('user_addresses.create_and_edit', ['address' => $user_address]);
    }

    public function update(Request $request)
    {

        $user = Auth::guard('api')->user();
        $address = UserAddress::find($request->id);

        if($address->user_id !== $user->id){
            return response()->json(['status'=>3000,'msg'=>'非法修改!']);
        }

        $address->address = $request->address;
        $address->contact_name = $request->contact_name;
        $address->contact_phone = $request->contact_phone;

        $bool = $address->save();

        if($bool){
            return response()->json(['meta'=>['status'=>200,'msg'=>'地址更新成功!'],'data'=>$address]);
        }else{
            return response()->json(['meta'=>['status'=>3000,'msg'=>'地址更新失败!'],'data'=>$address]);
        }


    }

    public function delete(Request $request)
    {

        $user_address = UserAddress::find($request->id);
        $bool = $user_address->delete();

        if($bool){
            return response()->json(['meta'=>['status'=>200,'msg'=>'地址删除成功!']]);
        }else{
            return response()->json(['meta'=>['status'=>3000,'msg'=>'地址删除失败!']]);
        }

    }
}
